<?php
/**
 * 邮件模板模块
 */
namespace app\controllers;
use app\models\LangImportExportForm;
use app\models\TemplateImportExportForm;
use Yii;
use yii\filters\AccessControl;
use yii\helpers\Html;
use yii\web\Controller;
use yii\filters\VerbFilter;
use app\models\Template;
use app\models\TemplateNew;
use yii\db\Query;
use yii\db\Command;
use yii\helpers\Url;
use yii\data\Pagination;
use app\components\TemplateMarket;
use app\components\EmailMarket;
use yii\web\UploadedFile;
use PHPExcel;

class MailTemplateController extends \app\base\Controller
{
	public $enableCsrfValidation = false;
        
        /*
         * 新的邮件模板列表
         */
        public function actionTemplateList()
        {
            $mothod = Yii::$app->request->getMethod();
            $site = Yii::$app->request->$mothod('site');
            $uuqid = Yii::$app->request->$mothod('uuqid');
            $uuqid = $uuqid ? trim($uuqid) : '';
            
            $defaultPageSize = 20;
            $pageSize = Yii::$app->request->$mothod('pagesize') ? Yii::$app->request->$mothod('pagesize') : $defaultPageSize;
                    // 当前用户所有有权限的站点
//            $siteInfo_tmp = Yii::$app->authority->getSysEmailAccessSite();
//
//            // $siteInfo[0] = '网站';
//            if (isset($siteInfo_tmp) && is_array($siteInfo_tmp)) {
//                foreach ($siteInfo_tmp as $siteInfo_tmp_k => $siteInfo_tmp_v) {
//                    $siteInfo[$siteInfo_tmp_v['site_id']] = $siteInfo_tmp_v['name'];
//                }
//            }
//
//            $formData['siteInfo'] = $siteInfo;
            
            $site_id = 12;
            
            $allUuqid = TemplateNew::getUuqidBySiteId($site_id);

            Yii::$app->db->enableSlaves = false;

            $where = " WHERE is_delete = 0 and site_id = $site_id ";      //只展示没有删除的模板
            
            if($uuqid) {
                $where .= " and uuqid = '{$uuqid}'";
            }
            
            //分页
            $totalCountSql = " SELECT COUNT(id) AS total FROM template_new " . $where ;
            // echo $totalCountSql;
            $totalCount = Yii::$app->db->createCommand($totalCountSql)->queryScalar();
            $pages = new Pagination(['totalCount' =>$totalCount, 'pageSize' => $pageSize, 'defaultPageSize' => $pageSize]);
            $pageCount = $pages->getPageCount(); //页数
            $pageOther = ['totalCount' => $totalCount, 'pageCount' => $pageCount];

            //模板数据
            $limit = " LIMIT {$pages->offset}, {$pages->limit}";
            $order = " ORDER BY id DESC ";
            $sql = " SELECT * FROM template_new " . $where . $order . $limit;
            $datas = Yii::$app->db->createCommand($sql)->queryAll();
            
            $templateIdArr = $langData = [];
            foreach($datas as $data) {
                $templateIdArr[] = $data['id'];
            }
            
            if($templateIdArr) {
                $getLangSql = "select template_id,count(*) nums from template_lang where is_enable = 1 and template_id in(".join(',', $templateIdArr).") group by template_id";
                $langInfos = Yii::$app->db->createCommand($getLangSql)->queryAll();
                foreach($langInfos as $langInfo) {
                    $langData[$langInfo['template_id']] = $langInfo['nums'];
                }
            }
            
            
            return $this->render('template-list',
                [
                    'site'=> $site,
                    'pages' => $pages,
                    'uuqidInfo'  => $allUuqid,
                    'langData'  => $langData,
                    'datas' => $datas,
                    'selectUuqid' => $uuqid,
                    'site_id'   => $site_id
                ]
            );
        }
        
	/**
	 * 邮件模板列表
	 */
	public function actionIndex() {

		$data = [];
        $siteInfo = [];
        $defaultPageSize = 20;

		// 当前用户所有有权限的站点
        $siteInfo_tmp = Yii::$app->authority->getSysEmailAccessSite();
        
        // $siteInfo[0] = '网站';
        if (isset($siteInfo_tmp) && is_array($siteInfo_tmp)) {
            foreach ($siteInfo_tmp as $siteInfo_tmp_k => $siteInfo_tmp_v) {
                $siteInfo[$siteInfo_tmp_v['site_id']] = $siteInfo_tmp_v['name'];
            }
        }

        $formData['siteInfo'] = $siteInfo;

        $authority_site_id = implode(',',array_keys($siteInfo));

        // echo "<pre>";
        // print_r($siteInfo);

        $mothod = Yii::$app->request->getMethod();
		//$site_id = Yii::$app->request->$mothod('site_id');   //网站id
        $site_id = !empty(Yii::$app->request->$mothod('site_id')) ? Yii::$app->request->$mothod('site_id') :12;    //网站id
		$cur_site = Yii::$app->request->$mothod('site');    //当前木块名称
        $reg_source = Yii::$app->request->$mothod('reg_source');    //注册来源
        $template_type_id = Yii::$app->request->$mothod('template_type_id');    //网站类型
        $is_add_anchors = Yii::$app->request->$mothod('is_add_anchors');    //是否添加锚点
        $is_advertis_id = Yii::$app->request->$mothod('is_advertis_id');    //是否有广告位
        
        
        $template_type_id = is_array($template_type_id) ? array_filter($template_type_id) : $template_type_id;
		$formData['site_id'] = !empty($site_id) ? $site_id : 0;
		$formData['is_add_anchors'] = $is_add_anchors;
		$formData['is_advertis_id'] = $is_advertis_id;
 
		$pageSize = Yii::$app->request->$mothod('pagesize') ? Yii::$app->request->$mothod('pagesize') : $defaultPageSize;

		$where = " WHERE is_delete = 0 ";      //只展示没有删除的模板

		if ( $site_id ) {   //选择了网站
			$where .= " AND site_id = " . $site_id ;
		} else {   //默认有权限的网站 
			$where .= " AND site_id in ( " . $authority_site_id . ")";
		}
                
                if($is_add_anchors == 1) {
                    $where .= " AND is_add_anchors = 1";
                } else if($is_add_anchors == 2) {
                    $where .= " AND is_add_anchors != 1";
                }
                if($is_advertis_id == 1) {
                    $where .= " AND is_add_advertis = 1";
                } else if($is_advertis_id == 2) {
                    $where .= " AND is_add_advertis != 1";
                }
                
		if ( ! empty($reg_source) && $reg_source != 'ALL') {
            $where .= " AND reg_source = '{$reg_source}' ";
        }
        

        if ( ! empty($template_type_id) && is_array($template_type_id)) {
            
            $where .= " AND template_type_id in(".join(',', $template_type_id).")";
        } else if(! empty($template_type_id)) {
            $where .= " AND template_type_id = {$template_type_id} ";
        }
//var_dump($where);
		//分页
		$totalCountSql = " SELECT COUNT(id) AS total FROM template " . $where ;
		// echo $totalCountSql;
		$totalCount = Yii::$app->db->createCommand($totalCountSql)->queryScalar();
		$pages = new Pagination(['totalCount' =>$totalCount, 'pageSize' => $pageSize, 'defaultPageSize' => $pageSize]);
        $pageCount = $pages->getPageCount(); //页数
        $pageOther = ['totalCount' => $totalCount, 'pageCount' => $pageCount];

        //模板数据
        $limit = " LIMIT {$pages->offset}, {$pages->limit}";
        $order = " ORDER BY id DESC ";
        $sql = " SELECT * FROM template " . $where . $order . $limit;
        $data = Yii::$app->db->createCommand($sql)->queryAll();
        // echo $sql;die;
        foreach ( $data as $key => $val ) {
        	$data[$key]['id'] = $val['id'];
        	$data[$key]['note'] = $val['note'];
        	$data[$key]['template_subject'] = $val['template_subject'];
        	foreach ( $siteInfo as $site_k => $site_v) {
        		if ( $val['site_id'] == $site_k ) {
        			$data[$key]['site_name'] = $site_v;
        			break;
        		}
        	} 
        	//$data[$key]['identify'] = $val['identify'];
        	$data[$key]['type'] = $val['type'] == 1 ? "纯文本邮件" : ($val['type'] == 2 ? "html邮件" : '');
        	$data[$key]['last_modify'] = yii::$app->systime->date($val['last_modify']);
        	$data[$key]['state'] = $val['state'];
        }

        $defRegSourceIndex = (empty($reg_source)) ? "ALL" : $reg_source;
        $defTemTypeListIndex = (empty($template_type_id)) ? [0] : $template_type_id;
        $reg_source = [];
        if ( ! empty($site_id)) {
            $reg_source = TemplateMarket::regSourceList($site_id);
            if(! empty($defRegSourceIndex) && $defRegSourceIndex != 'ALL') {
                $templateTypeList = Yii::$app->db->createCommand(
                    'select * from template_type where site_id = '.(int)$site_id ." and reg_source = '{$defRegSourceIndex}'")->queryAll();
            }else {
                $templateTypeList = Yii::$app->db->createCommand(
                    'select * from template_type where site_id = '.(int)$site_id )->queryAll();
            }
        }else {
            $reg_source= ['ALL'=> '全部'];
            $templateTypeList = [['id' => 0,'sys_template_type_description' => '全部']];
        }
        //$siteInfoDefualt = ['0' => '全部'];
        //$formData['siteInfo'][0] = '全部';6
        // var_dump($formData);die;
        //var_dump($formData);die;
        //  $result = Yii::$app->db->createCommand('select * from template_type where site_id = '.(int)$site_id)->queryAll();
        // 渲染模版
        return $this->render('list',[
            'data' => $data,
            'site' => $cur_site,
            'pages' => $pages,
            'pageOther' => $pageOther,
            'formData' => $formData,
            'regSource' => $reg_source,
            'templateTypeList' => $templateTypeList,
            'defRegSourceIndex' => $defRegSourceIndex,
            'defTemTypeListIndex' => $defTemTypeListIndex,
            // 'curPageIds' => $curPageIds,           
        ]);
	}
        
        /*
         * 预览有广告位的模板
         */
        public function actionPreview()
        {
            $method = yii::$app->request->getMethod();
            $id = yii::$app->request->$method('id');
            $id = $id ? intval($id) : 0;
            if(!$id) {
                $this->sysMsg('警告', '模板ID不存在!',$params = [ 'type' => 'error', 'links' => [ ['name'=>'返回上一页' , 'url'=>'javascript:history.go(-1)'] ] ]);
            }
            $model = new Template;
            $templateInfo = $model->getOneById($id);
            if($templateInfo['is_add_anchors'] == 1 && $templateInfo['is_add_advertis'] == 1) {
                
                return $this->render('preview',[
                    'data' => $templateInfo,       
                ]);
            } else {
                $this->sysMsg('警告', '模板未添加锚点或广告位!',$params = [ 'type' => 'error', 'links' => [ ['name'=>'返回上一页' , 'url'=>'javascript:history.go(-1)'] ] ]);
            }
        }
        /*
         * 保存广告位图片且关联到指定模板
         */
        public function actionBatchAddAdvertics()
        {
            $method = yii::$app->request->getMethod();
            $formData = yii::$app->request->$method();
            
            $site_id = $formData['site_id'] ? intval($formData['site_id']) : 0;
            $template_ids = $formData['template_ids'] ? trim($formData['template_ids']) : '';
            $advertis_type = isset($formData['advertis_type']) && $formData['advertis_type'] ? intval($formData['advertis_type']) : 0;
            $is_hidden_advertis = isset($formData['is_hidden_advertis']) ? intval($formData['is_hidden_advertis']) : 0;
            
            
            // 保存广告位图片数据
            $model = new Template;
            if($template_ids) {
                $model->updateTemplateAdvertis($site_id,$template_ids,$advertis_type,$formData,$is_hidden_advertis);
            }
            
            
            return json_encode(['code' => 0, 'msg' => 'success']);
        }
        /*
         *  判断选择的模板是否已经添加广告位锚点及是否是所选择的渠道来源模板
         * liugang
         */
        public function actionCheckAdvertisTemplate()
        {
            $method = yii::$app->request->getMethod();
            $site_id = yii::$app->request->$method('site_id');
            $reg_source = yii::$app->request->$method('reg_source');
            $template_ids = yii::$app->request->$method('template_ids');
            $site_id = intval($site_id);
            $reg_source = trim($reg_source);
            
            $return = ['code' => 1, 'msg' => '', 'datas' => []];
            if($template_ids) {
                $model = new Template;
                $return['datas'] = $model->checkAdvertisTemplate($site_id,$reg_source,$template_ids);
            } else {
                $return['code'] = 0;
                $return['msg'] = '请选择模板！';
            }
            return json_encode($return);
        }
    /**
     * 注册来源列表
     * author xianxuefeng
     * date 2018/4/26
     */
    public function actionRegSourceList() {
        $method = yii::$app->request->getMethod();
        $site_id = yii::$app->request->$method('site_id');
        $site_id = intval($site_id);
        if ( ! empty($site_id)) {
            $regSourceInfo = TemplateMarket::regSourceList($site_id);
        }else {
            $regSourceInfo= ['ALL'=> '全站'];
            //$regSourceInfo = [];
        }
//        $regSource = Html::dropDownList('reg_source',
//            'ALL',$regSourceInfo, ['class' => 'form-control z-select mr10 mb5']);

        $return = array(
            'status'  => 1,
           // 'datas'    => $regSource,
            'datas'    => $regSourceInfo,
            // 'display' => empty($regSourceInfo) ? false :true
        );
        echo json_encode($return);exit;
    }

	/**
	 * 邮件模板添加
	 */
	public function actionAdd() {
		$data = [];
		// 当前用户所有有权限的站点
        $siteInfo_tmp = Yii::$app->authority->getSysEmailAccessSite();
        
        if (isset($siteInfo_tmp) && is_array($siteInfo_tmp)) {
            foreach ($siteInfo_tmp as $siteInfo_tmp_k => $siteInfo_tmp_v) {
                $siteInfo[$siteInfo_tmp_v['site_id']] = $siteInfo_tmp_v['name'];
            }
        }
        
        // 邮件类型获取
//        $email_template_type = Yii::$app->params['sites']['sys_email']['email_template_uuqid'];

        $mothod = strtolower(Yii::$app->request->getMethod());
        
		$id = !empty(Yii::$app->request->get('id')) ? Yii::$app->request->get('id') : 0;
		$site = Yii::$app->request->get('site');    //模块名称
        $siteId = !empty(Yii::$app->request->get('site_id')) ? Yii::$app->request->get('site_id') : 0;
		$model = new Template();
       
		//保存
		if ( Yii::$app->request->post() ) {
                    
			$id = !empty(Yii::$app->request->post('id')) ? Yii::$app->request->post('id') : 0;
			$site_id = !empty(Yii::$app->request->post('site_id')) ? Yii::$app->request->post('site_id') : 0;
			$subject = !empty(Yii::$app->request->post('subject')) ? Yii::$app->request->post('subject') : '';
			$note = !empty(Yii::$app->request->post('note')) ? Yii::$app->request->post('note') : '';
			$type = !empty(Yii::$app->request->post('type')) ? Yii::$app->request->post('type') : 0;
			$content = !empty(Yii::$app->request->post('content')) ? Yii::$app->request->post('content') : '';
			//对特殊字符进行处理
			$content   = str_replace('%7B','{',$content);
                        $content   = str_replace('%7D','}',$content);
                        $content   = str_replace('&amp;','&',$content);
                        
                        $is_add_anchors = 0;
                        if(preg_match('%<i id="add_advertis_anchors_pos">(.*?)</i>%i', $content, $match)) {
                            $is_add_anchors = 1;
                        }
                        $is_add_advertis = 0;
                        if(isset($match[1]) && $match[1]) {
                            $is_add_advertis = 1;
                        }
                       
			$uuqid = !empty(Yii::$app->request->post('uuqid')) ? Yii::$app->request->post('uuqid') : '' ;
			$state = !empty(Yii::$app->request->post('state')) ? Yii::$app->request->post('state') : 0;
			$track_code = !empty(Yii::$app->request->post('track_code')) ? Yii::$app->request->post('track_code') : 0;
			//author xianxuefeng 添加注册来源和邮件类型
            $reg_source = !empty(Yii::$app->request->post('reg_source')) ? Yii::$app->request->post('reg_source') : 0;
            $template_type_id = !empty(Yii::$app->request->post('template_type_id')) ? Yii::$app->request->post('template_type_id') : 0;
            $session        = Yii::$app->session;
            $admin_info     = $session['admin_info'];
            $addSaid = $admin_info['real_name'];
			if ( $id ) {    //修改
				$model = $model->findOne( $id );
			}
			if ( ! empty($state)) {
			    self::actionDelTemplateStartState(['site_id' => $site_id,'uuqid' => $uuqid]);
            }
            
			//  新增  修改
            if ( ! empty($site_id)) {
                $model->site_id = $site_id;
            }
            if (! empty($track_code)) {
			    //$track_code = rtrim($track_code,'{sendTime}');
                $model->em_track_code = $track_code;
            }
            if (! empty($reg_source)) {
                $model->reg_source = $reg_source;   // 添加修改者
            }

            if (! empty($uuqid)) {
                $model->uuqid = $uuqid;
            }

            $model->template_subject = $subject;
			$model->note = $note;
			$model->template_content = $content;
			$model->last_modify = yii::$app->systime->time();
			$model->type = $type;
			//$model->identify = 1;
			$model->state = $state;
			$model->add_said = $addSaid;   // 添加修改者
			$model->template_type_id = $template_type_id;    //模板类型id
			$model->is_add_anchors = $is_add_anchors;    //模板类型id
			$model->is_add_advertis = $is_add_advertis;    //模板类型id
            
			if ( $model->save() ) {
                            // 清理模板缓存
                            if($id && $state == 1) {
                                Template::clearCacheById($site_id,$id,$uuqid);
                            }
                            
                            return $this->redirect(['mail-template/index?site=sys_email']);
			}

		}
		//添加模板页面是返回注册来源列表
        $regSoureclist = TemplateMarket::regSourceList(12);   //默认返回gearbast 站的注册来源。
       
		//修改的数据展示页面
		if ( $id ) {   
			//获取该条记录的信息
			$data = $model->find()->where(['id' => $id])->one();
                        // 邮件类型获取           
		}

        $email_template_type = array();
        $site_id = !empty($id) ? (int)$data['site_id'] : $siteId;
        $site_id = !empty($site_id) ?: 12;

        if ($site_id) {
            $email_template_type = Yii::$app->db->createCommand('select * from template_type where site_id = '.(int)$site_id)->queryAll();
        }    
//        var_dump($siteInfo);die;

		//新增数据的展示页面
		$empty_data = array('id'=>'','site_id'=>'','template_subject'=>'','note'=>'','template_content'=>'','type'=>2,'uuqid'=>'','state'=>0, 'template_type_id' => '');

//        echo "<pre/>";
//        var_dump($data);
//        var_dump($siteInfo);
//        var_dump($email_template_type);
//        var_dump($site);
//        die;

		// 渲染模版
        return $this->render('add',[
            'data' => $id ? $data : $empty_data,
            'siteInfo' => $siteInfo,
            'siteId' => $siteId,
            'email_template_type'  => $email_template_type,
            'site' => $site,
            'regSource' => $regSoureclist,
        ]);

	}
        
        /*
         * 单封邮件语言模板编辑和添加
         */
        public function actionSingleTemplate()
        {
            
		$data = [];
		// 当前用户所有有权限的站点
                $siteInfo_tmp = Yii::$app->authority->getSysEmailAccessSite();

                if (isset($siteInfo_tmp) && is_array($siteInfo_tmp)) {
                    foreach ($siteInfo_tmp as $siteInfo_tmp_k => $siteInfo_tmp_v) {
                        $siteInfo[$siteInfo_tmp_v['site_id']] = $siteInfo_tmp_v['name'];
                    }
                }

		$site = Yii::$app->request->get('site');    //模块名称
                
                $siteId = 12; // 暂写死网站id
                
		$model = new TemplateNew();
                
                $id = Yii::$app->request->get('id') ? Yii::$app->request->get('id') : (Yii::$app->request->post('id') ? Yii::$app->request->post('id') : 0);
                
                $id = intval($id);
                
                if(!$id) {
                    $this->sysMsg('警告', '参数不正确!',$params = [ 'type' => 'error', 'links' => [ ['name'=>'返回上一页' , 'url'=>'javascript:history.go(-1)'] ] ]);
                }
               
        
                
                // 获取当前邮件类型的英语语言key数据，并拼接模板
                $templateInfo = $model->getTemplateByLang($id);
                
                if(!$templateInfo) {
                    $this->sysMsg('警告', '默认语言模板数据不存在!',$params = [ 'type' => 'error', 'links' => [ ['name'=>'返回上一页' , 'url'=>'javascript:history.go(-1)'] ] ]);
                }
                
                $langData = json_decode($templateInfo['data'], true);
//                var_dump($templateInfo);exit;
                
                $langArr = $addLangArr = [];
                foreach($langData as $lang => $data) {
                    if(is_array($data)) {
                        foreach($data as $key => $val) {
                            if(!is_array($val)) {
                                $langArr['{$'.$lang.'.'.$key.'}'] = $val;
                            }
                        }
                        continue;
                    }
                    $langArr['{$'.$lang.'}'] = $data; 
                }
                
                if($langArr) {
                    $replaceKeys = array_keys($langArr);
                    $replaceVals = array_values($langArr);
                    
                    $templateInfo['template_content'] = str_replace($replaceKeys, $replaceVals, $templateInfo['template_content']);
                }
                
                
                // 获取当前模板的语言
                $templateLangs = $model->getTemplateLangById($id);
                
                foreach($templateLangs as $templateLang) {
                    $addLangArr[] = $templateLang['lang'];
                }
                
                // 调用接口获取语言
		$langInfo = $this->getSiteLangs();
                
                $langInfo = json_decode($langInfo, true);
                if(!$langInfo || $langInfo['code'] != 0) {
                    $this->sysMsg('警告', '获取语言数据出错!',$params = [ 'type' => 'error', 'links' => [ ['name'=>'返回上一页' , 'url'=>'javascript:history.go(-1)'] ] ]);
                }
                
                
                $langData = [];
                foreach($langInfo['data'] as $lang) {
                    $langData[$lang['lang']]['name'] = $lang['name'];
                    if(in_array($lang['lang'], $addLangArr)) {
                        $langData[$lang['lang']]['is_add'] = 1;
                    } else {
                        $langData[$lang['lang']]['is_add'] = 0;
                    }
                }
//                var_dump($langData);exit;
		// 渲染模版
                return $this->render('single-template',[
                    'templateInfo'  => $templateInfo,
                    'langInfo'  => $langData,
                    'defaultLang' => isset($langData[$templateInfo['lang']]['name']) ? $langData[$templateInfo['lang']]['name'] : '',
                    'siteInfo' => $siteInfo,
                    'siteId' => $siteId,
                    'site' => $site,
                ]);

	
        }
        
        /**
         * 单封邮件模版提交
         */
        public function actionSaveSingleTemplate()
        {

                    //保存
            $return = ['code' => 0, 'message' => 'success', 'data' => []];
            if ( $post = Yii::$app->request->post() ) {

                $id = $post['id'] ? intval($post['id']) : 0;
                            
                $lang = $post['lang'] ? trim($post['lang']) : '';
                            
                $subject = $post['subject'] ? trim($post['subject']) : '';
                $data = $post['data'] ? trim($post['data']) : '';
                $is_enable = isset($post['is_enable']) ? intval($post['is_enable']) : 1;
                
                // 英语版本不允许关闭
                if($lang == 'en'){
                    $is_enable = 1;
                }
                
                $data = json_decode($data, true);
                if(!$data) {
                    $return['code'] = 2;
                    $return['message'] = '模板语言数据不正确!';
                    return json_encode($return);
                    exit;
                }
                $data = json_encode($data);
                $curTime = yii::$app->systime->time();

                $session        = Yii::$app->session;
                $admin_info     = $session['admin_info'];
                $addSaid = $admin_info['real_name'];
                
                $insertSql = 'insert into template_lang(`template_id`,`lang`,`subject`,`data`,`is_enable`,`add_user`,`add_time`) values('.$id.',"'.$lang.'","'.$subject.'",:data,'.$is_enable.',"'.$addSaid.'",'.$curTime.')'.
                        ' ON DUPLICATE KEY UPDATE subject=values(subject),data=values(data),is_enable=values(is_enable),update_user=values(add_user),update_time=values(add_time)';
                
                $param[":data"] = $data;
                
                if(Yii::$app->db->createCommand($insertSql)->bindValues($param)->execute()) {
                    
                    // 清理模板缓存
                    if($id) {
                        Yii::$app->db->enableSlaves = false;

                        $getTemplateDataSql = "select site_id,uuqid from template_new where id = $id";
                        $templateOne = Yii::$app->db->createCommand($getTemplateDataSql)->queryOne();
                        Template::newClearCacheById($templateOne['site_id'],$templateOne['uuqid'],$lang);
                    }
                    
                    return json_encode($return);
                } else {
                    $return['code'] = 2;
                    $return['message'] = '模板语言数据保存失败!';
                    return json_encode($return);
                }


            }
        }
        
        /**
         * 语言模板发送内测功能
         */
        public function actionSendInnerTest()
        {
            $mothod = Yii::$app->request->getMethod();
            $id = Yii::$app->request->$mothod('id'); 
            $lang = Yii::$app->request->$mothod('lang');
            $email = Yii::$app->request->$mothod('email');
            $site_id = Yii::$app->request->$mothod('site_id');
            
            $id = $id ?  intval($id) : 0;
            $lang = $lang ? trim($lang) : '';
            $email = $email ? trim($email) : '';
            $site_id = $site_id ? intval($site_id) : 12;
            
            $site_name = Yii::$app->params['sites']['sys_email']['web_index'][$site_id];
            
            
            $return = ['code' => 0, 'message' => 'success', 'data' => []];
            if(!$id || !$lang || !$email) {
                $return['code'] = 2;
                $return['message'] = '参数不正确！';
                return json_encode($return);
                exit;
            }
            
            // 验证邮箱格式
            $emailObj = new EmailMarket();
            if (!$emailObj->isEmail($email)) {
                $return['code'] = 2;
                $return['message'] = '收件人邮箱地址格式不正确！';
                return json_encode($return);
                exit;
            }
            
             // 过滤被AWS永久退回的邮箱地址拒绝发送
            if($emailObj->getOne($site_name, $email)) {
                $return['code'] = 2;
                $return['message'] = '此邮箱收件人之前有被永久退回过，被系统拒绝！';
                return json_encode($return);
                exit;
            }
            
            $model = new TemplateNew();
            // 获取当前邮件类型的英语语言key数据，并拼接模板
            $templateInfo = $model->getTemplateByLang($id, $lang);

            if(!$templateInfo) {
                $return['code'] = 2;
                $return['message'] = '语言模板数据不存在！';
                return json_encode($return);
                exit;
            }
            
            
            $simulatedData = json_decode($templateInfo['simulated_data'], true); // 语言邮件模拟数据
            $data = json_decode($templateInfo['data'] ,true); // 语言key数据
            
            $simulatedData['email'] = $email;
            $smartyVars = array_merge($simulatedData,$data);
            
            if (isset($templateInfo['em_track_code']) && ! empty($templateInfo['em_track_code'])) {
                $ymd = substr(yii::$app->bjTime->date("Ymd"),2);
                $ymd = trim($ymd);
                $templateInfo['em_track_code'] = trim($templateInfo['em_track_code']);

                $replaceArr = [
                    isset($smartyVars['siteCode']) ? $smartyVars['siteCode'] : 'GB',
                    isset($smartyVars['pipelineCode']) ? $smartyVars['pipelineCode'] : '',
                    $templateInfo['uuqid'],
                    $ymd
                ];
                $smartyVars['em_track_code'] = str_replace(['{site}','{channel}','{mailtype}','{senddate}'], $replaceArr, $templateInfo['em_track_code']);
            }
            
            //获取网站邮件发送人
            $from = Yii::$app->params['sites']['sys_email']['web_config'][$site_name]['from'];
            // 发送邮件
            try{
                $return = app()->mailer->compose()
                ->setTo($email)
                ->setFrom($from)
                ->sendInnerTest(
                    $templateInfo,
                    $smartyVars
                );
//                var_dump($return);exit;
            } catch (\Exception $e) {
                $return['code'] = 2;
//                $return['message'] = $e->getMessage().' '.$e->getFile().' '.$e->getTraceAsString();
                $return['message'] = $e->getMessage().' '.$e->getFile();
            }
//            var_dump($result);exit;
            return json_encode($return);
        }
        /**
         * 一步获取指定语言版本
         */
        public function actionGetLangDataByLang()
        {
            $mothod = Yii::$app->request->getMethod();
            $id = Yii::$app->request->$mothod('id'); 
            $lang = Yii::$app->request->$mothod('lang');
            $id = $id ?  intval($id) : 0;
            $lang = $lang ? trim($lang) : '';
            
            $return = ['code' => 1, 'msg' => 'success', 'data' => []];
            if(!$id || !$lang) {
                $return['code'] = 0;
                $return['msg'] = '参数不正确！';
                return json_encode($return);
                exit;
            }
            
            $model = new TemplateNew();
            // 获取当前邮件类型的英语语言key数据，并拼接模板
            $templateInfo = $model->getTemplateByLang($id, $lang);

            if(!$templateInfo) {
                $templateInfo = $model->getTemplateByLang($id);
            }
            
            if(!$templateInfo) {
                $return['code'] = 0;
                $return['msg'] = '语言模板数据不存在！';
                return json_encode($return);
                exit;
            }
            
            $langData = json_decode($templateInfo['data'], true);
//                var_dump($templateInfo);exit;

            $langArr = $addLangArr = [];
            foreach($langData as $lang => $data) {
                if(is_array($data)) {
                    foreach($data as $key => $val) {
                        if(!is_array($val)) {
                            $langArr['{$'.$lang.'.'.$key.'}'] = $val;
                        }
                    }
                    continue;
                }
                $langArr['{$'.$lang.'}'] = $data; 
            }

            if($langArr) {
                $replaceKeys = array_keys($langArr);
                $replaceVals = array_values($langArr);

                $templateInfo['template_content'] = str_replace($replaceKeys, $replaceVals, $templateInfo['template_content']);
            }
            
            $return['data'] = $templateInfo;
            
            return json_encode($return);
            exit;
        }
        /**
         * 调用接口获取语言信息
         */
        public function getSiteLangs()
        {
            
            $apiUrl = [
                'dev'  => 'http://work.gw-soa.com/api/pipeline/languages',
                'test' => 'http://work.gw-soa.com/api/pipeline/languages',
                'product' => 'http://work.gw-soa.com/api/pipeline/languages',
            ];
            
            $userAgent = [
                'dev'  => 'weitengfei003',
                'test' => 'weitengfei003',
            ];
            
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $apiUrl[YII_ENV]);
            if(isset($userAgent[YII_ENV])) {
                curl_setopt($ch, CURLOPT_USERAGENT, $userAgent[YII_ENV]);
            }
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
            curl_setopt($ch, CURLOPT_TIMEOUT, 30);
            
            $response_contents = curl_exec($ch);
            
            $response_Info = curl_getinfo($ch);
            curl_close($ch);
            
            return $response_contents;
//            var_dump($response_contents);exit;
//            $postData = [];
//            if(isset($userAgent[YII_ENV])) {
//                $postData['header']['User-Agent'] = $userAgent[YII_ENV];
//            }
//            
//            
//            try{
//                $client = new \GuzzleHttp\Client(['timeout' => 60]);
//                $response = $client->request('GET', $apiUrl[YII_ENV], ['json' => $postData]);
//                $responseJsonString = $response->getBody()->getContents();
//                $returnData = \GuzzleHttp\json_decode($responseJsonString,true);
//                
//                
//                $langArr = [];
//                if($returnData['code'] == 0) {
//                    foreach($returnData['data'] as $lang) {
//                        $langArr[$lang['default_lang']] = 0;
//                    }
//                }
//                
//                return $langArr;
//            } catch(\exception $e) {var_dump($postData);exit;
//                return 0;
//            }
        }
        /**
	 * 邮件模板添加
	 */
	public function actionNewAdd() {
		$data = [];
		// 当前用户所有有权限的站点
                $siteInfo_tmp = Yii::$app->authority->getSysEmailAccessSite();

                if (isset($siteInfo_tmp) && is_array($siteInfo_tmp)) {
                    foreach ($siteInfo_tmp as $siteInfo_tmp_k => $siteInfo_tmp_v) {
                        $siteInfo[$siteInfo_tmp_v['site_id']] = $siteInfo_tmp_v['name'];
                    }
                }

		$site = Yii::$app->request->get('site');    //模块名称
                
                $siteId = 12; // 暂写死网站id
                
		$model = new TemplateNew();
       
		//保存
		if ( $post = Yii::$app->request->post() ) {
                         
			$site_id = $post['site_id'] ? intval($post['site_id']) : 0;
			$is_have_track_code = !empty($post['is_have_track_code']) ? intval($post['is_have_track_code']) : 0;
                        
			$name = $post['name'] ? trim($post['name']) : '';
			$uuqid = $post['uuqid'] ? trim($post['uuqid']) : '';
			$template_content = $post['template_content'] ? trim($post['template_content']) : '';
			//对特殊字符进行处理
			$template_content   = str_replace('%7B','{',$template_content);
                        $template_content   = str_replace('%7D','}',$template_content);
                        $template_content   = str_replace('&amp;','&',$template_content);
                        
                       
			$template_lang_data = $post['template_lang_data'] ? trim($post['template_lang_data']) : '';
			$simulated_data = $post['simulated_data'] ? trim($post['simulated_data']) : '';
			$em_track_code = $post['em_track_code'] ? trim($post['em_track_code']) : '';
                        
                        $session        = Yii::$app->session;
                        $admin_info     = $session['admin_info'];
                        $addSaid = $admin_info['real_name'];
                        
                        $template_lang_arr = json_decode($template_lang_data, true);
                        $simulated_data_arr = json_decode($simulated_data, true);
                        
//                        var_dump($template_lang_data,$template_lang_arr);exit;
                        if(!$template_lang_data || !$template_lang_arr) {
                            $this->sysMsg('警告', '导入模板key不能为空或json格式不正确!',$params = [ 'type' => 'error', 'links' => [ ['name'=>'返回上一页' , 'url'=>'javascript:history.go(-1)'] ] ]);
                        }
                        if(!$simulated_data || !$simulated_data_arr) {
                            $this->sysMsg('警告', '导入模板数据不能为空或json格式不正确!',$params = [ 'type' => 'error', 'links' => [ ['name'=>'返回上一页' , 'url'=>'javascript:history.go(-1)'] ] ]);
                        }
                        if($name == '' || $model->find()->where(['name' => $name])->one()) {
                            $this->sysMsg('警告', '邮件类型已经存在!',$params = [ 'type' => 'error', 'links' => [ ['name'=>'返回上一页' , 'url'=>'javascript:history.go(-1)'] ] ]);
                        }
                        
                        if($uuqid == '' || $model->find()->where(['uuqid' => $uuqid])->one()) {
                            $this->sysMsg('警告', '模板标识字段已经存在!',$params = [ 'type' => 'error', 'links' => [ ['name'=>'返回上一页' , 'url'=>'javascript:history.go(-1)'] ] ]);
                        }
                        
			//  新增  修改
                        if ($site_id) {
                            $model->site_id = $site_id;
                        }
                        if (!empty($em_track_code)) {
                            
                            $model->em_track_code = $em_track_code;
                        }
                        $curTime = yii::$app->systime->time();
                        
                        $model->name = $name;
			$model->uuqid = $uuqid;
			$model->template_content = $template_content;
			$model->add_time = $curTime;
			$model->simulated_data = $simulated_data;
			$model->add_user = $addSaid;
            
			if ( $model->save() ) {
                            $inserId = Yii::$app->db->getLastInsertID();
                            if($inserId && $template_lang_data) {
                                $insertArr = $param = [];
                                $i=0;
                                $insertSql = 'insert into template_lang(`template_id`,`lang`,`subject`,`data`,`add_user`,`add_time`) values';
                                foreach($template_lang_arr as $template_lang) {
                                    
                                    $param[":data".$i] = json_encode($template_lang['data']);
                                    $insertArr[] = '('.$inserId.',"'.trim($template_lang['lang']).'","'.trim($template_lang['subject']).'",:data'.$i.',"'.$addSaid.'",'.$curTime.')';
                                    $i++;
                                }
                                if($insertArr) {
                                    $insertSql .= join(',', $insertArr).' ON DUPLICATE KEY UPDATE subject=values(subject),data=values(data)';
                                    Yii::$app->db->createCommand($insertSql)->bindValues($param)->execute();
                                }
                                
                            }
                            
                            return $this->redirect(['mail-template/template-list?site=sys_email']);
			}

		}


		// 渲染模版
                return $this->render('new-add',[
                    'siteInfo' => $siteInfo,
                    'siteId' => $siteId,
                    'site' => $site,
                ]);

	}

    /**
     * 邮件模板添加
     */
    public function actionDelete() {
        $return = ['status'=>1,'msg'=>'成功', 'okNum' => 1, 'badNum' => 0];
       // echo json_encode($return);exit;//输出数组信息
        //传入id为数组，is_delete为1，
        // 当前用户所有有权限的站点
        $siteInfo_tmp = Yii::$app->authority->getSysEmailAccessSite();
    
        if (isset($siteInfo_tmp) && is_array($siteInfo_tmp)) {
            foreach ($siteInfo_tmp as $siteInfo_tmp_k => $siteInfo_tmp_v) {
                $siteInfo[$siteInfo_tmp_v['site_id']] = $siteInfo_tmp_v['name'];
            }
        }
        $id = !empty(Yii::$app->request->get('id')) ? Yii::$app->request->get('id') : 0;
        //保存
        if ( $id ) {
            $model = Template::findOne($id);
            $model->is_delete =1;
            if($model->save()) {
                exit(json_encode(['status' => 1, 'msg' => '成功']));//输出数组信息
            }
        }
        $return = ['status'=>0,'msg'=>'系统繁忙'];
        exit(json_encode($return));//输出数组信息

    }
    
    /**
     * 删除邮件模板
     */
    public function actionNewDelete() {
        $return = ['status'=>1,'msg'=>'成功', 'okNum' => 1, 'badNum' => 0];
       // echo json_encode($return);exit;//输出数组信息
        //传入id为数组，is_delete为1，
        // 当前用户所有有权限的站点
       
        $id = !empty(Yii::$app->request->get('id')) ? Yii::$app->request->get('id') : 0;
        //保存
        if ( $id ) {
            $model = TemplateNew::findOne($id);
            $model->is_delete =1;
            if($model->save()) {
                exit(json_encode(['status' => 1, 'msg' => '成功']));//输出数组信息
            }
        }
        $return = ['status'=>0,'msg'=>'系统繁忙'];
        exit(json_encode($return));//输出数组信息

    }

    /**
     * 启动系统邮件判断
     */
    public function actionTemplateStartState() {
        $siteInfo_tmp = Yii::$app->authority->getSysEmailAccessSite();
        if (isset($siteInfo_tmp) && is_array($siteInfo_tmp)) {
            foreach ($siteInfo_tmp as $siteInfo_tmp_k => $siteInfo_tmp_v) {
                $siteInfo[$siteInfo_tmp_v['site_id']] = $siteInfo_tmp_v['name'];
            }
        }
        $params = Yii::$app->request->post();
        $response = ['status'=>0,'msg'=>'失败','data' =>['state' => 0 ]];
        if ( ! isset($params['uuqid']) && empty($params['uuqid'])) {
            $response['msg'] = 'uuqid不能为空';
            exit(json_encode($response));//输出数组信息
        }
        if ( ! isset($params['site_id']) && empty($params['site_id'])) {
            $response['msg'] = 'site_id不能为空';
            exit(json_encode($response));//输出数组信息
        }
        $model = new Template();
        $res = $model->find()->asArray()->where(['uuqid' => $params['uuqid'],'site_id' => $params['site_id'],'state' => 1])->one();
        if (empty($res)) {
            $response['status'] = 0;
            $response['msg'] = '失败';
            exit(json_encode($response));//输出数组信息
        }
        $response['status'] = 1;
        $response['msg'] = '成功';
        $response['data'] = ['state' => 1];
        exit(json_encode($response));//输出数组信息
    }

    /**
     * 启动系统邮件判断
     */
    private function actionDelTemplateStartState($params) {
        if ( ! isset($params['uuqid']) && empty($params['uuqid'])) {
           return false;
        }
        if ( ! isset($params['site_id']) && empty($params['site_id'])) {
           return false;
        }
        $sql = "update template set state = 0 where uuqid = '{$params['uuqid']}' and site_id = {$params['site_id']}";
        Yii::$app->db->createCommand($sql)->execute();
        return true;
    }




    /**
     * 邮件模板添加
     */
    public function actionEdit() {
        // 当前用户所有有权限的站点
        $siteInfo_tmp = Yii::$app->authority->getSysEmailAccessSite();
        if (isset($siteInfo_tmp) && is_array($siteInfo_tmp)) {
            foreach ($siteInfo_tmp as $siteInfo_tmp_k => $siteInfo_tmp_v) {
                $siteInfo[$siteInfo_tmp_v['site_id']] = $siteInfo_tmp_v['name'];
            }
        }
        $id = !empty(Yii::$app->request->get('id')) ? Yii::$app->request->get('id') : 0;
        $site = Yii::$app->request->get('site');    //模块名称
        $siteId = !empty(Yii::$app->request->get('site_id')) ? Yii::$app->request->get('site_id') : 0;
        $model = new Template();
         //获取该条记录的信息
        $sql = "select * from template where id = {$id}";
        $data =  yii::$app->db->createCommand($sql)->queryAll();
        $reg_source = TemplateMarket::regSourceList(12);
        if (isset($data[0]['reg_source']) && ! empty($data[0]['reg_source'])) {
            $data[0]['reg_source_name'] = $reg_source[$data[0]['reg_source']];
        }else {
            $data[0]['reg_source'] = 'ALL';  //全站
            $data[0]['reg_source_name'] = '全站';
        }
        $data[0]['site_name'] =  isset(Yii::$app->params['sites']['sys_email']['web_index'][$data[0]['site_id']])  
        ? Yii::$app->params['sites']['sys_email']['web_index'][$data[0]['site_id']] : "";
        // echo "<pre>";
        // print_R($data[0]);
        // print_r($siteId);
        // die;
        $siteId=12;
//        var_dump(($data));die;
        // 渲染模版
        return $this->render('edit',[
            'data' => $data[0],
            'siteInfo' => $siteInfo,
            'siteId' => $siteId,
            'site' => $site
        ]);
    }
    
    
    public function actionNewEdit() {
		$data = [];
		// 当前用户所有有权限的站点
                $siteInfo_tmp = Yii::$app->authority->getSysEmailAccessSite();

                if (isset($siteInfo_tmp) && is_array($siteInfo_tmp)) {
                    foreach ($siteInfo_tmp as $siteInfo_tmp_k => $siteInfo_tmp_v) {
                        $siteInfo[$siteInfo_tmp_v['site_id']] = $siteInfo_tmp_v['name'];
                    }
                }

		$site = Yii::$app->request->get('site');    //模块名称
		$id = Yii::$app->request->get('id');    
                $id = $id ? intval($id) : 0;
                
                $siteId = 12; // 暂写死网站id
                $templateInfo = [];
                
		$model = new TemplateNew();
                
                if($id) {
                    Yii::$app->db->enableSlaves = false;
                    // 获取模板数据
                    $templateInfo = Yii::$app->db->createCommand("select * from template_new where id=$id and is_delete=0")->queryOne();
                    $templateInfo['template_lang_data'] = '';
                    // 获取语言数据
                    if($templateInfo) {
                        $langData = Yii::$app->db->createCommand("select lang,subject,data from template_lang where template_id={$templateInfo['id']} and is_enable=1")->queryAll();

                        $langArr = [];
                        foreach($langData as $lang) {
                            $langArr[] = [
                                'lang' => $lang['lang'],
                                'subject' => $lang['subject'],
                                'data' => json_decode($lang['data'], true),
                            ];
                        }
                        
                        if($langArr) {
                            $templateInfo['template_lang_data'] = json_encode($langArr);
                        }
                    }
                }
                
		//保存
		if ( $post = Yii::$app->request->post() ) {
                         
			$site_id = $post['site_id'] ? intval($post['site_id']) : 0;
			$id = $post['id'] ? intval($post['id']) : 0;
			$is_have_track_code = !empty($post['is_have_track_code']) ? intval($post['is_have_track_code']) : 0;
                        
			$template_content = $post['template_content'] ? trim($post['template_content']) : '';
			//对特殊字符进行处理
			$template_content   = str_replace('%7B','{',$template_content);
                        $template_content   = str_replace('%7D','}',$template_content);
                        $template_content   = str_replace('&amp;','&',$template_content);
                        
                       
			$template_lang_data = $post['template_lang_data'] ? trim($post['template_lang_data']) : '';
			$simulated_data = $post['simulated_data'] ? trim($post['simulated_data']) : '';
                        
                        $session        = Yii::$app->session;
                        $admin_info     = $session['admin_info'];
                        $addSaid = $admin_info['real_name'];
                        
                        $template_lang_arr = json_decode($template_lang_data, true);
                        $simulated_data_arr = json_decode($simulated_data, true);
                        
//                        var_dump($id);exit;
                        if(!$id) {
                            $this->sysMsg('警告', '参数不正确!',$params = [ 'type' => 'error', 'links' => [ ['name'=>'返回上一页' , 'url'=>'javascript:history.go(-1)'] ] ]);
                        }
                        if(!$template_lang_data || !$template_lang_arr) {
                            $this->sysMsg('警告', '导入模板key不能为空或json格式不正确!',$params = [ 'type' => 'error', 'links' => [ ['name'=>'返回上一页' , 'url'=>'javascript:history.go(-1)'] ] ]);
                        }
                        if(!$simulated_data || !$simulated_data_arr) {
                            $this->sysMsg('警告', '导入模板数据不能为空或json格式不正确!',$params = [ 'type' => 'error', 'links' => [ ['name'=>'返回上一页' , 'url'=>'javascript:history.go(-1)'] ] ]);
                        }
                        
                        if ( $id ) {    //修改
				$model = $model->findOne( $id );
			}
			//  新增  修改
                        if ($site_id) {
                            $model->site_id = $site_id;
                        }
                        
                        $curTime = yii::$app->systime->time();
                        
			$model->template_content = $template_content;
			$model->update_time = $curTime;
			$model->simulated_data = $simulated_data;
			$model->update_user = $addSaid;
            
			if ( $model->save() ) {
                            if($id && $template_lang_data) {
                                $insertArr = $param = [];
                                $i=0;
                                $insertSql = 'insert into template_lang(`template_id`,`lang`,`subject`,`data`,`add_user`,`add_time`) values';
                                foreach($template_lang_arr as $template_lang) {
                                    
                                    $param[":data".$i] = json_encode($template_lang['data']);
                                    $insertArr[] = '('.$id.',"'.trim($template_lang['lang']).'","'.trim($template_lang['subject']).'",:data'.$i.',"'.$addSaid.'",'.$curTime.')';
                                    $i++;
                                }
                                if($insertArr) {
                                    $insertSql .= join(',', $insertArr).' ON DUPLICATE KEY UPDATE subject=values(subject),data=values(data),update_user=values(add_user),update_time=values(add_time)';
                                    Yii::$app->db->createCommand($insertSql)->bindValues($param)->execute();
                                }
                                
                            }
                            
                             // 清理模板缓存
                            if($id) {
                                Template::newClearCacheById($site_id,$model->uuqid);
                            }
                            
                            return $this->redirect(['mail-template/template-list?site=sys_email']);
			}

		}


		// 渲染模版
                return $this->render('new-edit',[
                    'siteInfo' => $siteInfo,
                    'siteId' => $siteId,
                    'site' => $site,
                    'templateInfo'  => $templateInfo
                ]);

	}

	//批量导入指定语言的所有邮件语言数据
	public function actionLangImport()
    {
        $site = Yii::$app->request->get('site');    //模块名称
        // 获取语言列表
        $langInfo = $this->getSiteLangs();
        $langInfo = json_decode($langInfo, true);
        if(!$langInfo || $langInfo['code'] != 0) {
            $this->sysMsg('警告', '获取语言数据出错!',$params = [ 'type' => 'error', 'links' => [ ['name'=>'返回上一页' , 'url'=>'javascript:history.go(-1)'] ] ]);
        }
        $langData = [];
        foreach($langInfo['data'] as $lang) {
            $langData[$lang['lang']] = $lang['name'];
        }

        //用户信息
        $session        = Yii::$app->session;
        $admin_info     = $session['admin_info'];
        $user = $admin_info['real_name'];

        $time = yii::$app->systime->time();

        $model = new LangImportExportForm();
        //上传文件、写入数据库
        if (Yii::$app->request->isPost) {
            $model->load(Yii::$app->request->post());
            $uploadFile = UploadedFile::getInstance($model, 'excelFile');
            $uploadFilePath = Yii::$app->getRuntimePath().'/uploads/'.$site.'/';
            if (!file_exists($uploadFilePath)) {
                mkdir($uploadFilePath, 0777, true);
            }
            $uploadFileName = $uploadFilePath . $uploadFile->baseName. '_'. $user. '_'. date('YmdHis') . '.' . $uploadFile->extension;
            $uploadFile->saveAs($uploadFileName);

            $reader = \PHPExcel_IOFactory::createReaderForFile($uploadFileName);
            $phpExcel = $reader->load($uploadFileName);
            $sheetCount = $phpExcel->getSheetCount();
            for ($i = 0; $i < $sheetCount; $i++) {
                $currentSheet = $phpExcel->getSheet($i);
                $sheetName = $currentSheet->getTitle();
                $rowCount = $currentSheet->getHighestRow();
                //获取subject
                $subject = $currentSheet->getCell('B1')->getValue();
                //获取data
                $data = [];
                for ($rowIndex = 2; $rowIndex <= $rowCount; $rowIndex++) {
                    $key = $currentSheet->getCell('A'.$rowIndex)->getValue();
                    $value = $currentSheet->getCell('B'.$rowIndex)->getValue();
                    if ($value instanceof \PHPExcel_RichText) {//富文本转换字符串
                        $value = $value->__toString();
                    }

                    if (strpos($key, '.') !== false) {
                        list($containerKey, $langKey) = explode('.', $key);
                        $data[$containerKey][$langKey] = $value;
                    } else {
                        $data[$key] = $value;
                    }

                }

                //写入数据
                $templateQuerySql = "select id from `template_new` where name=:name";
                $templateRecord = Yii::$app->db->createCommand($templateQuerySql)->bindValues([':name'=>$sheetName])->queryOne();
                if (empty($templateRecord)) {
                    echo '模板:'.$sheetName.'不存在';exit;
                }
                $templateId = $templateRecord['id'];

                $params = [
                    ':lang'=>$model->lang,
                    ':subject'=>$subject,
                    ':data'=>json_encode($data)
                ];

                $insertSql = "insert into template_lang(`template_id`,`lang`,`subject`,`data`,`add_user`,`add_time`) values ($templateId, :lang, :subject, :data, '$user', '$time') ON DUPLICATE KEY UPDATE `subject`=values(`subject`),`data`=values(`data`),`update_user`=values(`add_user`),`update_time`=values(`add_time`)";
                $affectedRows = Yii::$app->db->createCommand($insertSql)->bindValues($params)->execute();
                if ($affectedRows > 0) {
                    echo $sheetName.'导入成功',"<br/>";
                } else {
                    echo $sheetName.'，导入失败',"<br/>";
                }

            }
            //清除模板
            $templateCache = new Template();
            $templateCache->delFileCache(12);

        }
        return $this->render('lang-import',[
            'site'=>$site,
            'langData'=>$langData,
            'model'=>$model
        ]);
    }


    //批量导出指定语言的所有邮件语言数据
    public function actionLangExport()
    {
        $site = Yii::$app->request->get('site');    //模块名称
        // 获取语言列表
        $langInfo = $this->getSiteLangs();
        $langInfo = json_decode($langInfo, true);
        if(!$langInfo || $langInfo['code'] != 0) {
            $this->sysMsg('警告', '获取语言数据出错!',$params = [ 'type' => 'error', 'links' => [ ['name'=>'返回上一页' , 'url'=>'javascript:history.go(-1)'] ] ]);
        }
        $langData = [];
        foreach($langInfo['data'] as $lang) {
            $langData[$lang['lang']] = $lang['name'];
        }
        $model = new LangImportExportForm();
        if (Yii::$app->request->isPost) {
            $model->load(Yii::$app->request->post());
            $langCode = $model->lang;
            $langName = $langData[$langCode];
            $sql = "select a.subject,a.data,b.name from `template_lang` a left join `template_new` b on a.template_id=b.id where a.lang='$langCode'";
            $result = Yii::$app->db->createCommand($sql)->queryAll();
            $phpExcel = new PHPExcel();
            foreach($result as $key=>$item) {
                $name = $item['name'];
                $subject = $item['subject'];
                $data = json_decode($item['data'], true);
                if ($key != 0) {
                    $phpExcel->createSheet();
                }
                $phpExcel->setActiveSheetIndex($key);
                $sheet = $phpExcel->getActiveSheet();
                $sheet->setTitle($name);

                $excelData = [];
                $excelData[] = ['subject', $subject];
                foreach($data as $containerKey => $containerValue) {
                    if (is_array($containerValue)) {
                        foreach($containerValue as $langKey => $langValue) {
                            $excelData[] = [$containerKey.'.'.$langKey, $langValue];
                        }
                    } else {
                        $excelData[] = [$containerKey, $containerValue];
                    }
                }
                $sheet->fromArray($excelData);

            }
            $phpExcel->setActiveSheetIndex(0);
            //下载
            header('Content-Type: application/vnd.ms-excel');
            header("Content-Disposition: attachment; filename=\"{$langName}国家站各邮件翻译.xls\"");
            header('Cache-Control: max-age=0');
            $writer = \PHPExcel_IOFactory::createWriter($phpExcel, 'Excel2007');
            $writer->save('php://output');
        }
        return $this->render('lang-export',[
            'site'=>$site,
            'langData'=>$langData,
            'model'=>$model
        ]);
    }

    //批量导入指定邮件的所有多语言数据
    public function actionTemplateImport()
    {
        $site = Yii::$app->request->get('site');    //模块名称

        //用户信息
        $session        = Yii::$app->session;
        $admin_info     = $session['admin_info'];
        $user = $admin_info['real_name'];

        $time = yii::$app->systime->time();

        //查询模板列表
        $templateQuerySql = "select `id`,`name`, `uuqid` from template_new";
        $templateResult = Yii::$app->db->createCommand($templateQuerySql)->queryAll();
        $templates = $templateUuqids = [];
        foreach($templateResult as $item) {
            $templates[$item['id']] = $item['name'];
            $templateUuqids[$item['id']] = $item['uuqid'];
        }

        $model = new TemplateImportExportForm();
        if (Yii::$app->request->isPost) {
            $model->load(Yii::$app->request->post());
            $templateId = $model->templateId;
            $uuqid = $templateUuqids[$templateId];
            $uploadFile = UploadedFile::getInstance($model, 'excelFile');
            $uploadFilePath = Yii::$app->getRuntimePath().'/uploads/'.$site.'/';
            if (!file_exists($uploadFilePath)) {
                mkdir($uploadFilePath, 0777, true);
            }
            $uploadFileName = $uploadFilePath . $uploadFile->baseName. '_'. $user. '_'. date('YmdHis') . '.' . $uploadFile->extension;
            $uploadFile->saveAs($uploadFileName);

            $reader = \PHPExcel_IOFactory::createReaderForFile($uploadFileName);
            $phpExcel = $reader->load($uploadFileName);
            $sheetCount = $phpExcel->getSheetCount();
            for ($i = 0; $i < $sheetCount; $i++) {
                $currentSheet = $phpExcel->getSheet($i);
                $sheetName = $currentSheet->getTitle();
                $rowCount = $currentSheet->getHighestRow();
                //获取subject
                $subject = $currentSheet->getCell('B1')->getValue();
                //获取data
                $data = [];
                for ($rowIndex = 2; $rowIndex <= $rowCount; $rowIndex++) {
                    $key = $currentSheet->getCell('A'.$rowIndex)->getValue();
                    $value = $currentSheet->getCell('B'.$rowIndex)->getValue();
                    if ($value instanceof \PHPExcel_RichText) {//富文本转换字符串
                        $value = $value->__toString();
                    }

                    if (strpos($key, '.') !== false) {
                        list($containerKey, $langKey) = explode('.', $key);
                        $data[$containerKey][$langKey] = $value;
                    } else {
                        $data[$key] = $value;
                    }

                }

                //写入数据
                $params = [
                    ':lang'=>$sheetName,
                    ':subject'=>$subject,
                    ':data'=>json_encode($data)
                ];

                $insertSql = "insert into template_lang(`template_id`,`lang`,`subject`,`data`,`add_user`,`add_time`) values ($templateId, :lang, :subject, :data, '$user', '$time') ON DUPLICATE KEY UPDATE `subject`=values(`subject`),`data`=values(`data`),`update_user`=values(`add_user`),`update_time`=values(`add_time`)";
                $affectedRows = Yii::$app->db->createCommand($insertSql)->bindValues($params)->execute();
                if ($affectedRows > 0) {
                    echo $sheetName.'导入成功',"<br/>";
                } else {
                    echo $sheetName.'，导入失败',"<br/>";
                }

            }
            //清除模板
            $templateCache = new Template();
            $templateCache->delFileCache(12, $uuqid);
        }
        return $this->render('template-import',[
            'site'=>$site,
            'templates'=>$templates,
            'model'=>$model
        ]);

    }

    //批量导出指定邮件的所有多语言数据
    public function actionTemplateExport()
    {
        $site = Yii::$app->request->get('site');    //模块名称

        //查询模板列表
        $templateQuerySql = "select `id`,`name` from template_new";
        $templateResult = Yii::$app->db->createCommand($templateQuerySql)->queryAll();
        $templates = [];
        foreach($templateResult as $item) {
            $templates[$item['id']] = $item['name'];
        }

        $model = new TemplateImportExportForm();
        if (Yii::$app->request->isPost) {
            $model->load(Yii::$app->request->post());
            $templateId = $model->templateId;
            $templateName = $templates[$templateId];
            $templateLangQuerySql = "select `lang`,`subject`,`data` from template_lang where template_id=:template_id";
            $templateLangResult = Yii::$app->db->createCommand($templateLangQuerySql)->bindValues([':template_id'=>$templateId])->queryAll();
            $phpExcel = new PHPExcel();
            foreach($templateLangResult as $key=>$item) {
                $lang = $item['lang'];
                $subject = $item['subject'];
                $data = json_decode($item['data'], true);
                if ($key != 0) {
                    $phpExcel->createSheet();
                }
                $phpExcel->setActiveSheetIndex($key);
                $sheet = $phpExcel->getActiveSheet();
                $sheet->setTitle($lang);

                $excelData = [];
                $excelData[] = ['subject', $subject];
                foreach($data as $containerKey => $containerValue) {
                    if (is_array($containerValue)) {
                        foreach($containerValue as $langKey => $langValue) {
                            $excelData[] = [$containerKey.'.'.$langKey, $langValue];
                        }
                    } else {
                        $excelData[] = [$containerKey, $containerValue];
                    }
                }
                $sheet->fromArray($excelData);

            }
            $phpExcel->setActiveSheetIndex(0);
            //下载
            header('Content-Type: application/vnd.ms-excel');
            header("Content-Disposition: attachment; filename=\"{$templateName}模板各语言数据.xls\"");
            header('Cache-Control: max-age=0');
            $writer = \PHPExcel_IOFactory::createWriter($phpExcel, 'Excel2007');
            $writer->save('php://output');

        }
        return $this->render('template-export',[
            'site'=>$site,
            'templates'=>$templates,
            'model'=>$model
        ]);

    }

    /**
     * 删除系统邮件模板缓存
     */
    public function actionDelTemplateCache()
    {
        $siteId = Yii::$app->request->get('site_id');
        $uuqid = Yii::$app->request->get('uuqid');
        $lang = Yii::$app->request->get('lang');
        $cacheDir = Yii::getAlias('@runtime/sys_template_cache');
        //如果删除指定模板的指定语言版本
        if($siteId && $uuqid && $lang){
            unlink($cacheDir.'/'.$siteId.'/'.$uuqid.'/'.$lang);
            return;
        }
        //如果没有指定语言版本，则删除该模板的所有语言版本
        if($siteId && $uuqid){
            $path = $cacheDir.'/'.$siteId.'/'.$uuqid;
            //exec(sprintf("rm -rf %s", escapeshellarg($path)));
            $this->rrmdir($path);
            return;
        }
        //如果只提供了站点ID，则删除该站点所有的模板缓存
        if($siteId){
            $path = $cacheDir.'/'.$siteId;
            //exec(sprintf("rm -rf %s", escapeshellarg($path)));
            $this->rrmdir($path);
        }
        return;
	}

    /**
     * 递归删除目录，先写在这里，后面再挪到公共的里面去
     * @param string $src 路径
     */
    private function rrmdir($src) {
        $dir = opendir($src);
        while(false !== ( $file = readdir($dir)) ) {
            if (( $file != '.' ) && ( $file != '..' )) {
                $full = $src . '/' . $file;
                if ( is_dir($full) ) {
                    $this->rrmdir($full);
                } else {
                    unlink($full);
                }
            }
        }
        closedir($dir);
        rmdir($src);
    }


        /*
         * 添加对应站点的模板类型
         */
        public function actionAddTemplateType()
        {
            $mothod = Yii::$app->request->getMethod();
            $site_id = Yii::$app->request->$mothod('site_id');   //网站id
            $sys_template_type_description = Yii::$app->request->$mothod('template_type_name');
            $sys_template_type_uuqid = Yii::$app->request->$mothod('template_type_compaign');
            $reg_source = Yii::$app->request->$mothod('reg_source');

            $return = ['status'=>1,'msg'=>'success'];

            if(!$site_id)
            {
                $return = ['status'=>0,'msg'=>'网站信息不存在！'];
                echo json_encode($return);exit;//输出数组信息
            }
            if(!$sys_template_type_description || !$sys_template_type_uuqid)
            {
                $return = ['status'=>0,'msg'=>'模板类型数据不能为空！'];
                echo json_encode($return);exit;//输出数组信息
            }
            // 查看数据有没有重复

            $totalCountSql = "SELECT count(id) from template_type where sys_template_type_description = '{$sys_template_type_description}' and site_id ={$site_id}";

            $totalCount = Yii::$app->db->createCommand($totalCountSql)->queryScalar();

            if ($totalCount) { // 说明类型重复
               $return = ['status'=>0,'msg'=>'该邮件类型已存在！'];
                echo json_encode($return);exit;//输出数组信息
            }

            $totalCountSql = "SELECT count(id) from template_type where sys_template_type_uuqid = '{$sys_template_type_uuqid}' and site_id ={$site_id}";

            $totalCount = Yii::$app->db->createCommand($totalCountSql)->queryScalar();

            if ($totalCount) { // 说明类型重复
               $return = ['status'=>0,'msg'=>'该类型标识已存在！'];
                echo json_encode($return);exit;//输出数组信息
            }

            if (empty($reg_source)) {     //添加注册来源
                $reg_source = 'ALL';
            }

            $insertData = array(
                'site_id'  => $site_id,
                'sys_template_type_uuqid'  => $sys_template_type_uuqid,
                'sys_template_type_description'  => $sys_template_type_description,
                'reg_source' => $reg_source,
                'add_time'              => time()
            );

            if(!Yii::$app->db->createCommand()->insert('template_type', $insertData)->execute())
            {
                $return = ['status'=>0,'msg'=>'模板类型数据添加失败！'];
                echo json_encode($return);exit;//输出数组信息
            }

            echo json_encode($return);//输出数组信息
        }
        /*
         * 获取指定站点的模板类型
         * site_id
         * reg_source
         * site
         */
        public function actionGetTemplateType()
        {
            $mothod = Yii::$app->request->getMethod();
            //$site = Yii::$app->request->$mothod('site');
            $site_id = Yii::$app->request->$mothod('site_id');
            $reg_source = Yii::$app->request->$mothod('reg_source');
            $return = ['status'=>1,'msg'=>'success','datas'=>[]];
            if(!$site_id)
            {
                $return = ['status'=>0,'msg'=>'网站信息不存在！','datas'=>[]];
                echo json_encode($return);exit;;//输出数组信息
            }
            if (! empty($reg_source) && $reg_source != 'ALL') {
                $sql = "select * from template_type where site_id = {$site_id} and reg_source = '{$reg_source}'";
            }else {
                $sql = "select * from template_type where site_id = {$site_id} ";
            }
            $result = Yii::$app->db->createCommand($sql)->queryAll();
            if($result)
            {
                $return['datas'] = $result;
            }
            echo json_encode($return);exit;
        }
        
        /*
         * 清理redis模板缓存
         */
        public function actionClearCache()
        {
            $templateModel = new Template;
            $templateModel->clearCache();
            return '缓存清理成功！';
        }
        
        /*
         * 清理redis模板缓存
         */
        public function actionNewClearCache()
        {
            $templateModel = new Template;
            $templateModel->newClearCache();
            return '缓存清理成功！';
        }
}
